package hotel.compare.oversea.controller;

import hotel.base.oversea.controller.BaseController;
import hotel.base.oversea.utils.DateUtil;
import hotel.base.oversea.utils.FileUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.utils.StringUtil;
import hotel.compare.oversea.config.service.RedisService;
import hotel.compare.oversea.entity.master.SpiderHotelLog;
import hotel.compare.oversea.mapper.master.SpiderHotelLogMapper;
import hotel.compare.oversea.service.SpiderHotelLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 校验后酒店
 * @author Zhang·JZ
 * @date 2020-05-28
 */
@Slf4j
@RestController
@RequestMapping("/tripSpider")
@Api(value = "TripSpiderController", tags = {"爬虫接口"})
public class TripSpiderController extends BaseController {


    @Autowired
    private SpiderHotelLogMapper spiderHotelLogMapper;


    @Autowired
    private SpiderHotelLogService spiderHotelLogService;


    private static String UPLOADED_FOLDER = System.getProperty("user.dir")+"/uploadFiles/";


    //返回内容
    private String loadMsg = "spider_hotel_load_msg_key";

    //是否开启爬虫功能 0 : null 关闭； 1：开启
    private String isStartSpider = "is_start_spider";


    @Autowired
    private RedisService redisService;

    /**
     * 获取当日爬取的酒店列表
     *
     * @return
     */
    @PostMapping("/getTripSpiderHotelList")
    @ApiOperation(value = "获取当日爬取的酒店列表")
    public Result getSpiderTripHotelList(@RequestBody(required = false) String nowDate) {
//        List<SpiderHotelLog> spiderHotelLogList = new ArrayList<>();
//        Example example = new Example(SpiderHotelLog.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("createTime",nowDate);
//        example.setOrderByClause(" is_agent asc ");
//        spiderHotelLogList = spiderHotelLogMapper.selectByExample(example);

        return new Result<>(new Object[]{"请联系技术人员做导出！"});
    }


    /**
     * 爬取当前上架携程酒店的在售房型
     *
     * @return
     */
    @PostMapping("/tripOnlineHotelSpiderSaleRoomList")
    @ApiOperation(value = "爬取当前上架携程酒店的在售房型")
    public Result tripOnlineHotelSpiderSaleRoomList() {

        return new Result<>(new Object[]{"请联系技术人员做导出！"});
    }




    /**
     * 导入需要爬取的酒店列表
     *
     * @return
     */
    @PostMapping("/importExcelSpiderHotel")
    @ApiOperation(value = "导入需要爬取的酒店列表")
    public Result importExcelSpiderHotel(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {

        //獲取file 文件存儲到文件夾
        byte[] bytes = excelFile.getBytes();
        String filePath = UPLOADED_FOLDER + excelFile.getOriginalFilename();
        Path path = Paths.get(filePath);
        Files.write(path, bytes);
        List<SpiderHotelLog> addList = new ArrayList<>();

        List<SpiderHotelLog> spiderHotelLogList = FileUtil.importExcel(filePath,0,1,SpiderHotelLog.class);
        spiderHotelLogList.forEach(spiderHotelLog->{
            if(!ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelId()) && !ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelName())){
                int switchsHotelId = spiderHotelLog.getSwitchsHotelId();
                String switchsHotelName = spiderHotelLog.getSwitchsHotelName();
                log.info("SwitchsHotelId---->>>>>{}",spiderHotelLog.getSwitchsHotelId());
                SpiderHotelLog spiderHotelLogNew = new SpiderHotelLog();
                spiderHotelLogNew.setId(StringUtil.getUUID());
                spiderHotelLogNew.setSwitchsHotelId(switchsHotelId);
                spiderHotelLogNew.setSwitchsHotelName(switchsHotelName);
                spiderHotelLogNew.setCreateTime(DateUtil.getToday());
                spiderHotelLogNew.setModifyTime(new Date());
                spiderHotelLogNew.setState(0);
                spiderHotelLogNew.setIsAgent(0);//默认没有代理
                addList.add(spiderHotelLogNew);
            }
        });
        int retInt = 0;
        boolean ret = false;
        if(!addList.isEmpty() && addList.size()>0){
            SpiderHotelLog spiderHotelLog = new SpiderHotelLog();
            spiderHotelLog.setCreateTime(DateUtil.getToday());
            retInt = spiderHotelLogMapper.delete(spiderHotelLog);
            if(retInt != -1){
                retInt = spiderHotelLogMapper.insertList(addList);

                if(retInt != -1){
                    try {
                        ret = spiderHotelLogService.tripSpiderHotelAgentByIsCreate(addList);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        log.info("爬虫执行--->>>{} ;新增成功--->>> {} 条数据",ret,retInt);
        return new Result(retInt);
    }


    /**
     * 爬取的酒店列表
     *
     * @return
     */
    @PostMapping("/tripSpiderHotelAll")
    @ApiOperation(value = "爬取的酒店列表")
    public Result tripSpiderHotelAll() throws IOException {

        List<SpiderHotelLog> addList = new ArrayList<>();

        List<SpiderHotelLog> spiderHotelLogList = spiderHotelLogMapper.spiderHotelAll();
        spiderHotelLogList.forEach(spiderHotelLog->{
            if(!ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelId()) && !ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelName())){
                int switchsHotelId = spiderHotelLog.getSwitchsHotelId();
                String switchsHotelName = spiderHotelLog.getSwitchsHotelName();
//                log.info("SwitchsHotelId---->>>>>{}",spiderHotelLog.getSwitchsHotelId());
                SpiderHotelLog spiderHotelLogNew = new SpiderHotelLog();
                spiderHotelLogNew.setId(StringUtil.getUUID());
                spiderHotelLogNew.setSwitchsHotelId(switchsHotelId);
                spiderHotelLogNew.setSwitchsHotelName(switchsHotelName);
                spiderHotelLogNew.setCreateTime(DateUtil.getToday());
                spiderHotelLogNew.setModifyTime(new Date());
                spiderHotelLogNew.setState(0);
                spiderHotelLogNew.setIsAgent(0);//默认没有代理
                addList.add(spiderHotelLogNew);
            }
        });
        int retInt = 0;
        boolean ret = false;
        if(!addList.isEmpty() && addList.size()>0){
            SpiderHotelLog spiderHotelLog = new SpiderHotelLog();
            spiderHotelLog.setCreateTime(DateUtil.getToday());
            retInt = spiderHotelLogMapper.delete(spiderHotelLog);
            if(retInt != -1){
                retInt = spiderHotelLogMapper.insertList(addList);

                if(retInt != -1){
                    try {
                        ret = spiderHotelLogService.tripSpiderHotelAgentByIsCreate(addList);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        log.info("爬虫执行--->>>{} ;新增成功--->>> {} 条数据",ret,retInt);
        return new Result(retInt);
    }


    /**
     *
     * 爬取的校验酒店列表中不是代理的酒店数据
     *
     * @param type 0:爬取校验酒店中所有数据；
     *             1：爬取校验酒店中是代理的酒店数据
     *             2：爬取校验酒店中不是代理的酒店数据
     * @return
     * @throws IOException
     */
    @PostMapping("/tripSpiderHotelByCompareHotel")
    @ApiOperation(value = "爬取的校验酒店列表中不是代理的酒店数据")
    public Result tripSpiderHotelByCompareHotel(@RequestBody(required = false) String type) throws IOException {

        //判断是否存在,为空说明未开启
        if(redisService.exists(loadMsg)){
            return new Result(new Object[]{"爬取中,请勿重复操作"});
        }

        List<SpiderHotelLog> addList = new ArrayList<>();

        redisService.set(loadMsg,"正在查询需要爬取的酒店数据,请稍后......");
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        List<SpiderHotelLog> spiderHotelLogList = new ArrayList<>();
        if("0".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotel();
        }else if("1".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotelIsAgent();
        }else if("2".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotelIsNotAgent();
        }

//        log.info("正在遍历需要爬取的数据----spiderHotelLogList.size>>>>>{}",spiderHotelLogList.size());
        redisService.set(loadMsg,"正在遍历需要爬取的数据,请稍后......");
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        spiderHotelLogList.forEach(spiderHotelLog->{
            if(!ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelId()) && !ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelName())){
                int switchsHotelId = spiderHotelLog.getSwitchsHotelId();
                String switchsHotelName = spiderHotelLog.getSwitchsHotelName();
                SpiderHotelLog spiderHotelLogNew = new SpiderHotelLog();
                spiderHotelLogNew.setId(StringUtil.getUUID());
                spiderHotelLogNew.setSwitchsHotelId(switchsHotelId);
                spiderHotelLogNew.setSwitchsHotelName(switchsHotelName);
                spiderHotelLogNew.setCreateTime(DateUtil.getToday());
                spiderHotelLogNew.setModifyTime(new Date());
                spiderHotelLogNew.setState(0);
                spiderHotelLogNew.setIsAgent(0);//默认没有代理
                addList.add(spiderHotelLogNew);
            }
        });

        redisService.set(loadMsg,"准备就绪开始爬取携程酒店数据,请稍后......");
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        int retInt = 1;
        boolean ret = false;
        if(!addList.isEmpty() && addList.size()>0){
            SpiderHotelLog spiderHotelLog = new SpiderHotelLog();
            spiderHotelLog.setCreateTime(DateUtil.getToday());
            retInt = spiderHotelLogMapper.delete(spiderHotelLog);
            if(retInt != -1){
                retInt = spiderHotelLogMapper.insertList(addList);

                if(retInt != -1){
                    try {
                        ret = spiderHotelLogService.tripSpiderHotelAgentByIsCreate(addList);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(retInt != 0){
            redisService.remove(loadMsg);
        }
        log.info("爬虫执行--->>>{} ;新增成功--->>> {} 条数据",ret,retInt);
        return new Result(new Object[]{"爬取完成"});
    }

    /**
     *
     * 爬取的校验酒店列表中不是代理的酒店数据
     *
     * @param type 0:爬取校验酒店中所有数据；
     *             1：爬取校验酒店中是代理的酒店数据
     *             2：爬取校验酒店中不是代理的酒店数据
     * @return
     * @throws IOException
     */
    @PostMapping("/tripSpiderHotelByCompareHotelOld")
    @ApiOperation(value = "爬取的校验酒店列表中不是代理的酒店数据")
    public Result tripSpiderHotelByCompareHotelOld(@RequestBody(required = false) String type) throws IOException {

        //判断是否存在,为空说明未开启
        if(redisService.exists(loadMsg)){
            return new Result(new Object[]{"爬取中,请勿重复操作"});
        }

        List<SpiderHotelLog> addList = new ArrayList<>();

        redisService.set(loadMsg,"正在查询需要爬取的酒店数据,请稍后......");
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        List<SpiderHotelLog> spiderHotelLogList = new ArrayList<>();
        if("0".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotel();
        }else if("1".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotelIsAgent();
        }else if("2".equals(type)){
            spiderHotelLogList = spiderHotelLogMapper.tripSpiderHotelByCompareHotelIsNotAgent();
        }

//        log.info("正在遍历需要爬取的数据----spiderHotelLogList.size>>>>>{}",spiderHotelLogList.size());
        redisService.set(loadMsg,"正在遍历需要爬取的数据,请稍后......");
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        spiderHotelLogList.forEach(spiderHotelLog->{
//            if(!ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelId()) && !ObjectUtils.isEmpty(spiderHotelLog.getSwitchsHotelName())){
//                int switchsHotelId = spiderHotelLog.getSwitchsHotelId();
//                String switchsHotelName = spiderHotelLog.getSwitchsHotelName();
//                SpiderHotelLog spiderHotelLogNew = new SpiderHotelLog();
//                spiderHotelLogNew.setId(StringUtil.getUUID());
//                spiderHotelLogNew.setSwitchsHotelId(switchsHotelId);
//                spiderHotelLogNew.setSwitchsHotelName(switchsHotelName);
//                spiderHotelLogNew.setCreateTime(DateUtil.getToday());
//                spiderHotelLogNew.setModifyTime(new Date());
//                spiderHotelLogNew.setState(0);
//                spiderHotelLogNew.setIsAgent(0);//默认没有代理
//                addList.add(spiderHotelLogNew);
//            }
//        });

        redisService.set(loadMsg,"准备就绪开始爬取携程酒店数据,请稍后......");
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        int retInt = 1;
        boolean ret = false;
        if(!addList.isEmpty() && addList.size()>0){
            SpiderHotelLog spiderHotelLog = new SpiderHotelLog();
            spiderHotelLog.setCreateTime(DateUtil.getToday());
            retInt = spiderHotelLogMapper.delete(spiderHotelLog);
            if(retInt != -1){
                retInt = spiderHotelLogMapper.insertList(addList);

                if(retInt != -1){
                    try {
                        ret = spiderHotelLogService.tripSpiderHotelAgentByIsCreate(addList);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if(retInt != 0){
            redisService.remove(loadMsg);
        }
        log.info("爬虫执行--->>>{} ;新增成功--->>> {} 条数据",ret,retInt);
        return new Result(new Object[]{"爬取完成"});
    }

    /**
     * 导出当天没有代理的酒店数据
     *
     * @return
     */
    @GetMapping("/exportSpiderFaileByToday")
    @ApiOperation(value = "获取当前爬取数量")
    public void exportSpiderFaileByToday() {
//        FileUtil.exportExcel();
    }


    /**
     * 获取当日爬取的酒店列表
     *
     * @return
     */
    @PostMapping("/getSpiderLoadNum")
    @ApiOperation(value = "获取当前爬取数量")
    public Result getSpiderLoadNum() {
        String ret = "";
        if(redisService.exists(loadMsg)){
            ret = (String) redisService.get(loadMsg);
            log.info("ret111>>{}",ret);
        }
        return new Result(new Object[]{ret});
    }


    /**
     * 根据已有的酒店房型爬取是否有再售卖
     * @return
     */
    @GetMapping("/tripSpiderHotelRoomByHas")
    @ApiOperation(value = "根据已有的酒店房型爬取是否有再售卖")
    public Result tripSpiderHotelRoomByHas(){


        return new Result();
    }
}


